package com.hxd.tabactivityfragment.mvp.presenter

import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.support.v4.app.FragmentActivity
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hxd.tabactivityfragment.bean.UserInfoBean
import com.hxd.tabactivityfragment.mvp.base.IBasePresenter
import com.hxd.tabactivityfragment.mvp.model.MineModel
import com.hxd.tabactivityfragment.mvp.view.IMineView
import com.hxd.tabactivityfragment.ui.fragment.MineFragment
import com.hxd.tabactivityfragment.util.*
import com.mylhyl.superdialog.SuperDialog
import com.vondear.rxtool.RxFileTool
import com.vondear.rxtool.RxPictureTool
import com.vondear.rxtool.RxSPTool
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File

/**
 *  项目名：    FoodOrigins
 *  包名：      com.hxd.tabactivityfragment.mvp.presenter
 *  文件名:     MinePresenter
 *  创建者:     HXD
 *  创建时间:   2019/4/1 16:22
 *  描述:       TODO
 */

class MinePresenter(val fragment: MineFragment,
                    val activity: FragmentActivity,
                    val context:Context,
                    val token:String) :IBasePresenter{

    private val mMineModel by lazy { MineModel() }
    private var mMineView:IMineView? = null

    /**
     * 打开相机功能
     */
    fun takePhoto(){
        if (RxFileTool.isFileExists(mMineView!!.getPhotoUri())){
            RxFileTool.deleteFile(mMineView!!.getPhotoUri())
        }
        val imageUri = Uri.fromFile(mMineView!!.getPhotoUri())
        val intent = RxPictureTool.getOpenCameraIntent()
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        fragment.startActivityForResult(intent, StaticClassUtil.CAMERA_REQUEST_CODE)
    }

    /**
     * 显示Dialog
     */
    fun showDialog(fragmentActivity: FragmentActivity?, list: ArrayList<String>) {
        SuperDialog.Builder(fragmentActivity)
           .setCanceledOnTouchOutside(false)
           .setItems(list) {
               when(it){
                   //拍照
                   0 -> {
                       XXPermissions.with(fragmentActivity)
                           .permission(Permission.CAMERA) //不指定权限则自动获取清单中的危险权限
                           .request(object : OnPermission {
                               //权限获取成功
                               override fun hasPermission(granted: List<String>, isAll: Boolean) {
                                   mMineView!!.getPermissionSuccess()
                               }
                               //权限获取失败
                               override fun noPermission(denied: List<String>, quick: Boolean) {
                                   mMineView!!.getPermissionFail()
                               }
                           })
                   }
                   //从相册中选择
                   1 -> {
                       //调用相册
                       val intent = Intent(
                           Intent.ACTION_PICK,
                           MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                       )
                       fragment.startActivityForResult(intent, StaticClassUtil.ALBUM_REQUEST_CODE)
                   }
               }
           }
           .setNegativeButton("取消", null)
           .build()
    }

    /**
     * 初始化一些用户信息
     */
    fun initUserData(imageView: ImageView, textView:TextView){
        //把这些都放进主线程里面去操作
        ThreadUtil.runOnMainThread(Runnable {
            val result = RxSPTool.getString(context, "userInfo")
            L.i("result: $result")
            if ( token != "" && result != ""){
                val userInfo = GsonToBean.JsonToBean<UserInfoBean>(result)
                L.i("urlImagePath $userInfo.msg.headerSrc")
                if (userInfo.msg.headerSrc != null){
                    val urlImagePath = URLProviderUtils.getUserHeaderUrl() + userInfo.msg.headerSrc
                    L.i("urlImagePath $urlImagePath")
                    Glide.with(context!!).
                        load(urlImagePath).
                        into(imageView)
                }else{
                    val imagePath = RxSPTool.getString(context!!, "photoPath")
                    L.i("imagePath : $imagePath")
                    if (imagePath!!.isNotEmpty()){
                        Glide.with(context!!).load(imagePath).into(imageView)
                    }
                }
                textView.text = userInfo.msg.name
            }
        })
    }

    /**
     * 调用相册功能
     */
    fun callAlbum(data: Intent, imageView:ImageView){
        ThreadUtil.runOnMainThread(Runnable {
            val selectedImage = data.data
            val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = activity!!.contentResolver.query(selectedImage, filePathColumns, null, null, null)
            cursor.moveToFirst()
            val columnIndex = cursor.getColumnIndex(filePathColumns[0])
            val imagePath = cursor.getString(columnIndex)
            //加载图片
            val bm = BitmapFactory.decodeFile(imagePath)
            Glide.with(context!!).load(bm).into(imageView)

            //进行图片压缩
            Luban.with(context).load(imagePath).ignoreBy(100).setCompressListener(object : OnCompressListener {
                //压缩成功后调用，返回压缩后的图片文件
                override fun onSuccess(file: File?) {
                   mMineModel.uploadImage(token, file!!, object : MineModel.OnUploadResultListener{
                       override fun UploadCallMsg(msg: String) {
                           mMineView!!.getDataFail(msg)
                           RxSPTool.putString(context!!, "userInfo", msg)
                       }
                   })
                }

                //当压缩过程出现问题时调用
                override fun onError(e: Throwable?) {
                    mMineView!!.getDataFail("压缩过程出现问题")
                }

                //当压缩过程出现开始时
                override fun onStart() {
                    mMineView!!.getDataFail("开始进行压缩")
                }

            }).launch()
            RxSPTool.putString(context, "photoPath",imagePath)
            cursor.close()
        })
    }

    /**
     * 调用相机功能
     */
    fun callCamera(imageView:ImageView){
        ThreadUtil.runOnMainThread(Runnable {
            Glide.with(context!!).load(mMineView!!.getPhotoUri()).into(imageView)
            L.i("photoPath : ${mMineView!!.getPhotoUri()}")
            RxSPTool.putString(context, "photoPath", "${mMineView!!.getPhotoUri()}")
        })
    }

    /**
     * 解绑
     */
    override fun destoryView() {
        if (mMineView != null){
            mMineView = null
        }
    }

    /**
     * 绑定
     */
    override fun bindView(view: Any) {
        mMineView = view as IMineView
    }
}